﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.App.Api.Application.Command.Basic;
using Traceability.App.ErrorCount;
using Traceability.App.InfrasIntructure;
using Traceability.App.Model;
using Traceability.App.Model.DeepProcessing;

namespace Traceability.App.Api.Application.Handler.Basic
{
    public class UpdateBasicHandler : IRequestHandler<UpdateBasicCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<BasicModel> _basicRepo;
        private readonly IBaseRepository<DeepProcessingCompanyModel> _deepProcessRepo;
        private readonly IMapper _mapper;

        public UpdateBasicHandler(IBaseRepository<BasicModel> basicRepo,IBaseRepository<DeepProcessingCompanyModel> deepProcessRepo,IMapper mapper)
        {
            _basicRepo = basicRepo;
            _deepProcessRepo = deepProcessRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdateBasicCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            // 检查生产批次是否重复（排除当前ID）
            var batchExists = await _basicRepo.GetAll().Where(c => c.Batch == request.Batch && !c.IsDeleted && c.Id != request.Id).AnyAsync();

            if (batchExists)
            {
                res.Msg = "存在更新的同批次数据，请修改最新记录";
                res.Code = ApiEnum.Error;
                return res;
            }

            // 获取要修改的基础信息
            var basic = await _basicRepo.GetAll().FirstOrDefaultAsync(x => !x.IsDeleted && x.Id == request.Id);
            if (basic == null)
            {
                res.Msg = "找不到编号";
                res.Code = ApiEnum.Fail;
                return res;
            }

            // 只更新最新的一条深加工企业记录
            if (!string.IsNullOrEmpty(request.License))
            {
                var latestDeepProcessCompany = await _deepProcessRepo.GetAll().Where(c => c.Batch == request.Batch && !c.IsDeleted).OrderByDescending(c => c.Id) .FirstOrDefaultAsync();

                if (latestDeepProcessCompany != null)
                {
                    latestDeepProcessCompany.LicenseNum = request.License;
                    await _deepProcessRepo.Update(latestDeepProcessCompany);
                }
            }

            // 更新基础信息
            _mapper.Map(request, basic);
            basic.Updator = request.Updator;
            basic.UpdatorDate = DateTime.Now;

            var result = await _basicRepo.Update(basic);
            res.Datas = result;
            res.Code = result > 0 ? ApiEnum.Success : ApiEnum.Fail;
            res.Msg = result > 0 ? "修改基本信息成功" : "修改基本信息失败";

            return res;
        }
    }
}
